package com.example.tse.rbyair.login.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.example.tse.rbhttpservice.service.HttpService;
import com.example.tse.rbhttpservice.service.RemoteServiceFactory;
import com.example.tse.rbhttpservice.service.RemoteServiceListenerT;
import com.example.tse.rbhttpservice.service.account.model.AccountRegisterRequest;
import com.example.tse.rbhttpservice.service.account.model.AccountRegisterResponse;
import com.example.tse.rbhttpservice.service.account.model.AccountSendVcodeRequest;
import com.example.tse.rbhttpservice.service.account.model.AccountSendVcodeResponse;
import com.example.tse.rbyair.R;
import com.example.tse.rbyair.login.LoginActivity;
import com.example.tse.rbyair.util.ClearEditText;
import com.example.tse.rbyair.util.CountDownButtonHelper;
import com.example.tse.rbyair.util.SharedPreferenceUtils;

import org.kymjs.kjframe.log.L;

import butterknife.Bind;
import butterknife.ButterKnife;

public class ReginsterFragment extends Fragment implements OnClickListener {


    @Bind(R.id.phoneEtxt)
    ClearEditText phoneEtxt;
    @Bind(R.id.codeEtxt)
    ClearEditText codeEtxt;
    @Bind(R.id.getcodeBtn)
    Button getcodeBtn;
    @Bind(R.id.pwdTxt)
    ClearEditText pwdTxt;
    @Bind(R.id.registerBtn)
    Button registerBtn;
    private View view;
    //	private EditText phoneEtxt;
//	private EditText pwdTxt;
//	private Button getcodeBtn;
//	private Button registerBtn;
//	private EditText codeEtxt;
    private boolean hasgetcode = false;
    private boolean isHidden = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        this.view = view;
        ButterKnife.bind(this, view);
        initView();
    }

    private void initView() {
//        phoneEtxt = (EditText) view.findViewById(R.id.phoneEtxt);
//        pwdTxt = (EditText) view.findViewById(R.id.pwdTxt);
//        ClearEditText phoneEtxt = (ClearEditText) view.findViewById(R.id.phoneEtxt);
//        getcodeBtn = (Button) view.findViewById(R.id.getcodeBtn);
        getcodeBtn.setOnClickListener(this);
//        registerBtn = (Button) view.findViewById(R.id.registerBtn);
        registerBtn.setOnClickListener(this);
//        codeEtxt = (EditText) view.findViewById(R.id.codeEtxt);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.getcodeBtn:
                if (checkPhone()) {
                    CountDownButtonHelper helper = new CountDownButtonHelper(getcodeBtn, "获取验证码", 60, 1);
                    helper.setOnFinishListener(new CountDownButtonHelper.OnFinishListener() {

                        @Override
                        public void finish() {

                        }
                    });
                    helper.start();
                    String phoneTxt = phoneEtxt.getText().toString();
                    getVerifyCode(phoneTxt, "2");
                }
                break;

            case R.id.registerBtn:
                if (checkRegistInfo()) {
                    String phoneTxt = phoneEtxt.getText().toString();
                    String codeTxt = codeEtxt.getText().toString();
                    String passWord = pwdTxt.getText().toString();
                    regist(phoneTxt, codeTxt,passWord);
                }
                break;
            default:
                break;
        }
    }

    private boolean checkPhone() {
        String telRegex = "[1][3578]\\d{9}";
        if (!phoneEtxt.getText().toString().trim().matches(telRegex)) {
            Toast.makeText(getActivity(), R.string.pleaseinputcorrectphone, Toast.LENGTH_LONG).show();
            return false;
        } else {
            return true;
        }
    }

    private boolean checkPwd() {
        String s = pwdTxt.getText().toString().trim();
        if (!TextUtils.isEmpty(s) && s.length() >= 6 && s.length() <= 16) {
            return true;
        } else {
            return false;
        }
    }


    private void getVerifyCode(final String phone, final String type) {

        /**
         *   发送验证码
         *   phone   :手机号
         *   type: 类型，1忘记密码、2用户注册
         */
        AccountSendVcodeRequest vcodeRequest = new AccountSendVcodeRequest() {
            @Override
            public String givePhone() {
                return phone;
            }

            @Override
            public String giveType() {
                return type;
            }
        };
        RemoteServiceFactory.getInstance().getAccountService(getActivity()).sendVcode(vcodeRequest, new RemoteServiceListenerT<AccountSendVcodeResponse>() {
            @Override
            public void okData(AccountSendVcodeResponse accountSendVcodeResponse) {
                super.okData(accountSendVcodeResponse);
//                accountSendVcodeResponse.
                hasgetcode = true;
                Toast.makeText(getActivity(), R.string.veritycodesendsuccess, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onMessage(String message) {
                super.onMessage(message);
                L.d("DemoListActivity vcodeRequest message:" + message);
            }

//        AccountSendVcodeRequest r = new AccountSendVcodeRequest();
//        r.setPhone(phoneEtxt.getText().toString().trim());
//        r.setType("2");
//        RemoteServiceFactory.getInstance().getAccountService(getActivity()).sendVcode(r, new RemoteServiceListener<AccountSendVcodeResponse>() {
//
//            @Override
//            public void ok(AccountSendVcodeResponse t) {
//                hasgetcode = true;
//                BaseToast.showCenterToast(R.string.veritycodesendsuccess, false);
//            }
//
//            @Override
//            public void failue(int errorCode, String errorMessage) {
//                BaseToast.showCenterToast(errorMessage, true);
//            }
        });

    }

    private boolean checkRegistInfo() {
        if (hasgetcode) {
            if (TextUtils.isEmpty(codeEtxt.getText().toString().trim())) {
                Toast.makeText(getActivity(), R.string.pleaseinputveritycode, Toast.LENGTH_LONG).show();
                return false;
            } else if (!checkPwd()) {
                Toast.makeText(getActivity(), R.string.pleaseinputcorrectpwd, Toast.LENGTH_LONG).show();
                return false;
            } else {
                return true;
            }
        } else {
            Toast.makeText(getActivity(), R.string.pleasegetveritycodefirst, Toast.LENGTH_LONG).show();
            return false;
        }
    }

    private void regist(final String phone, final String vcode, final String pwd) {

        AccountRegisterRequest registRequest = new AccountRegisterRequest() {
            @Override
            public String givePhone() {
                return phone;
            }

            @Override
            public String giveVcode() {
                return vcode;
            }

            @Override
            public String givePassword() {
                return pwd;
            }
        };
        RemoteServiceFactory.getInstance().getAccountService(getActivity()).register(registRequest, new RemoteServiceListenerT<AccountRegisterResponse>() {
            @Override
            public void okData(AccountRegisterResponse accountRegisterResponse) {
                super.okData(accountRegisterResponse);
                L.d("lichun", "ReginsterFragment accountRegisterResponse:" + accountRegisterResponse);
//                accountRegisterResponse.get
                SharedPreferenceUtils.putValueAndKey(getActivity(), "userToken", HttpService.token);
                SharedPreferenceUtils.putValueAndKey(getActivity(), "memberId", accountRegisterResponse.getMemberId());

                SharedPreferenceUtils.putValueAndKey(getActivity(), "isLoaded", "1");

                startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().finish();
            }

            @Override
            public void onMessage(String message) {
                super.onMessage(message);
                L.d("lichun", "ReginsterFragment message:" + message);
            }
        });

//		showLoadingDialog("注册中...");
//        AccountRegisterRequest r = new AccountRegisterRequest();
//        r.setPhone(phoneEtxt.getText().toString().trim());
//        r.setVcode(codeEtxt.getText().toString().trim());
//        r.setPassword(pwdTxt.getText().toString().trim());
//        RemoteServiceFactory.getInstance().getAccountService(getActivity()).register(r, new RemoteServiceListener<AccountRegisterResponse>() {
//
//            @Override
//            public void ok(AccountRegisterResponse t) {
////				dismissLoadingDialog();
//                BaseToast.showCenterToast(R.string.registsuccess, false);
//                RbLog.i(t.toString());
//
//                RbLog.i("userToken=" + RemoteServiceFactory.getInstance().getUserToken());
//                SharedPreferenceUtils.putValueAndKey(getActivity(), "userToken", RemoteServiceFactory.getInstance().getUserToken());
//
//                SharedPreferenceUtils.putValueAndKey(getActivity(), "memberId", t.getMemberId());
//
//                CommonUtils.isExited = false;
//                SharedPreferenceUtils.putValueAndKey(getActivity(), "isLoaded", "1");
//
//                startActivity(new Intent(getActivity(), LoginActivity.class));
//                getActivity().finish();
//            }
//
//            @Override
//            public void failue(int errorCode, String errorMessage) {
////				dismissLoadingDialog();
//                RbLog.i("errorMessage=" + errorMessage);
//                BaseToast.showCenterToast(errorMessage, true);
//            }
//        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
